package com.example.hans.navigationbyviewpageandradiobutton;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChartActivity extends AppCompatActivity{
    private static Socket mSocket;
    private EditText editText;
    private TextView textView;
    private Button button;

    private ImageView imageView;
    private TextView contactName;
    private byte request[] = new byte[2048];

    private String host = "120.79.66.125";
    private int port = 6666;//端口9999使用java做服务端  6666使用c语言的libev做服务端

    private RecyclerView mRecyclerView;
    private MsgAdapterForRecyclerView mMsgAdapterForRecyclerView;
    private List<Msg> msgList = new ArrayList<>();

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case 1: {
                    Msg msg1 = new Msg(msg.obj.toString(),Msg.TYPE_RECEIVED);
                    msgList.add(msg1);
                    mMsgAdapterForRecyclerView.notifyItemInserted(msgList.size()-1);
                    mRecyclerView.scrollToPosition(msgList.size()-1);
                    Log.d("123456",msg.obj.toString());
//                    textView.setText(textView.getText().toString()+"\nserver say:"+msg.obj);
                    break;
                }
                default:
                    super.handleMessage(msg);
            }
        }
    };

    public void hideTheTitleBar() {
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
            );
        }
    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_chart_view);
//
//        //隐藏标题栏函数
////        hideTheTitleBar();
//
//        Intent intent = getIntent();
//        String name = intent.getStringExtra("name");
//
//        button = (Button) findViewById(R.id.btn_submit);
//        editText = (EditText) findViewById(R.id.editxt_write);
//        textView = (TextView) findViewById(R.id.tv_show);
//        imageView = findViewById(R.id.Img_back);
//        contactName = findViewById(R.id.tv_showName);
//        contactName.setText(name);
//        imageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                finish();
//            }
//        });
//
//
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                String etRequest = editText.getText().toString();
//                editText.setText("");
//                try {
//                    OutputStream outputStream = mSocket.getOutputStream();
//                    request = etRequest.getBytes();
//                    outputStream.write(request,0,etRequest.length());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
//
//        new Thread(mSocketRunnable).start();
//
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_view);

        //隐藏标题栏函数
//        hideTheTitleBar();

        Intent intent = getIntent();
        String name = intent.getStringExtra("name");

        button = (Button) findViewById(R.id.send);
        editText = (EditText) findViewById(R.id.et_input);
        editText.setOnKeyListener(onKey);


        //设置RecyclerView界面  即信息界面
        mRecyclerView = findViewById(R.id.msg_recycler_view);
        mMsgAdapterForRecyclerView = new MsgAdapterForRecyclerView(msgList);
        mRecyclerView.setAdapter(mMsgAdapterForRecyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        imageView = findViewById(R.id.Img_back);

        //顶部组件
        contactName = findViewById(R.id.tv_showName);
        contactName.setText(name);





        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                try {
                    if (mSocket != null) {
                        mSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String etRequest = editText.getText().toString();


                if (!etRequest.equals("")) {
                    editText.setText("");
                    Log.d("123456",etRequest);
                    Msg msg = new Msg(etRequest,Msg.TYPE_SEND);
                    msgList.add(msg);
                    mMsgAdapterForRecyclerView.notifyItemInserted(msgList.size()-1);
                    mRecyclerView.scrollToPosition(msgList.size()-1);

                    try {
                        send(etRequest);
//                        OutputStream outputStream = mSocket.getOutputStream();
//                        request = etRequest.getBytes();
//                        outputStream.write(request,0,etRequest.length());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }



            }
        });

        new Thread(mSocketRunnable).start();

    }

    private View.OnKeyListener onKey=new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                //这里写发送信息的方法
                String etRequest = editText.getText().toString();
                if (!etRequest.equals("")) {
                    editText.setText("");
                    Log.d("123456",etRequest);
                    Msg msg = new Msg(etRequest,Msg.TYPE_SEND);
                    msgList.add(msg);
                    mMsgAdapterForRecyclerView.notifyItemInserted(msgList.size()-1);
                    mRecyclerView.scrollToPosition(msgList.size()-1);

                    try {
                        send(etRequest);
//                        OutputStream outputStream = mSocket.getOutputStream();
//                        request = etRequest.getBytes();
//                        outputStream.write(request,0,etRequest.length());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }
            return false;
        }
    };

    public void send(String str) throws Exception
    {
        DataOutputStream dos = new DataOutputStream(mSocket.getOutputStream());
        dos.writeUTF(str);
    }

    private Runnable mSocketRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                mSocket = new Socket("120.79.66.125",6666);


                DataInputStream dis = new DataInputStream(mSocket.getInputStream());
                String str = dis.readUTF();
                while (str != null && str.length() != 0)
                {
//                    System.out.println(str);
                    str = dis.readUTF();
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = str;
                    mHandler.sendMessage(msg);
                    if (str.equals("exit")) {
                        break;
                    }
                }


//                InputStream inputStream = mSocket.getInputStream();
//                while (true) {
//                    int length = inputStream.read(request);
//                    String content = new String(request,0,length);
//                    Message msg = new Message();
//                    msg.what = 1;
//                    msg.obj = content;
//                    mHandler.sendMessage(msg);
//                    if (content.equals("exit")) {
//                        break;
//                    }
//                }
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    public  static void actionStart(Context context,String name) {
        Intent intent = new Intent(context,ChartActivity.class);
        intent.putExtra("name",name);
        context.startActivity(intent);
    }
}
